package com.pj.test;

import cn.dev33.satoken.fun.strategy.SaCorsHandleFunction;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
 * [Sa-Token 权限认证] 配置类 
 * @author click33
 *
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

	/**
	 * CORS 跨域处理策略
	 */
	@Bean
	public SaCorsHandleFunction corsHandle() {
		return (req, res, sto) -> {

			// SaManager.getLog().debug("----- 请求path={}  提交token={}", req.getRequestPath(), StpUtil.getTokenValue());

			// 获得客户端domain
			String origin = req.getHeader("Origin");
			if (origin == null) {
				origin = req.getHeader("Referer");
			}

			// ---------- 设置跨域响应头 ----------
			res
				// 允许第三方 Cookie
				.setHeader("Access-Control-Allow-Credentials", "true")
				// 允许指定域访问跨域资源
				.setHeader("Access-Control-Allow-Origin", origin)
				// 允许所有请求方式
				.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
				// 允许的header参数
				.setHeader("Access-Control-Allow-Headers", "x-requested-with,satoken")
				// 有效时间
				.setHeader("Access-Control-Max-Age", "3600")
			;

			// 如果是预检请求，则立即返回到前端
			SaRouter.match(SaHttpMethod.OPTIONS)
				.free(r -> System.out.println("--------OPTIONS预检请求，不做处理"))
				.back();
		};
	}

}
